package com.beiding.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ResourceUtils {


    //缩略图,生成四份.按照等级划分,添加缩略图后缀,从1到5,分别是源图片的80%,50%,30%,12%,5%
    public static String[] compress(String path) throws IOException {//path 是将要被缩略的图片路径
        return compress(new File(path));
    }


    public static String[] compress(File file) throws IOException {//path 是将要被缩略的图片路径

        String path = file.getAbsolutePath();

        //图片文件
        Image image = ImageIO.read(file);

        //五个缩略图
        String[] r = new String[5];

        //添加缩略等级后缀
        r[0] = path + "-1";
        resize(image, r[0], 0.8);

        r[1] = path + "-2";
        resize(image, r[1], 0.5);

        r[2] = path + "-3";
        resize(image, r[2], 0.3);

        r[3] = path + "-4";
        resize(image, r[3], 0.12);

        r[4] = path + "-5";
        resize(image, r[4], 0.05);

        return r;


    }


    private static void resize(Image img, String outFile, double rank) throws IOException {
        int w = (int) (img.getWidth(null) * rank);
        int h = (int) (img.getHeight(null) * rank);
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, w, h, null);
        File destFile = new File(outFile);
        FileOutputStream out = new FileOutputStream(destFile);
        ImageIO.write(image, "gif", out);
        out.close();
    }


  /*  public static void main(String[] args) throws IOException {

        compress("C:\\Users\\dinglei\\Desktop\\test\\5C354A7FA2EC05DEEBB64B6AE3A092AB.jpg");

    }
*/

}
